package com.sh.cloudrender.domian.service.kube;

import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SvcService {

    @Autowired
    private CoreV1Api coreV1Api;


    public V1Service createSvc(String uid, String namespace,Integer containerPort) {
        V1Service service = getSvc(uid, namespace);
        if (service != null) {
            try {
                service = coreV1Api.replaceNamespacedService(uid, namespace, service, null, null,
                        null, null);
            } catch (ApiException e) {
                log.error("create uid:{} namespace:{} svc error, error msg:{}", uid, namespace, e.getResponseBody());
                return null;
            }

            return service;
        }

        // 使用 V1ServiceBuilder 构建 V1Service 对象
        service = new V1ServiceBuilder()
                .withApiVersion("v1")
                .withKind("Service")
                .withMetadata(new V1ObjectMeta()
                        .name(uid)
                        .namespace(namespace)
                        .putLabelsItem("uid", uid))
                .withSpec(new V1ServiceSpec()
                        .putSelectorItem("uid", uid)
                        .addPortsItem(new V1ServicePort()
                                .port(80)
                                .targetPort(new IntOrString(containerPort)))
                        .type("ClusterIP"))
                .build();
        V1Service resp = null;
        try {
            resp = coreV1Api.createNamespacedService(namespace, service, null, null, null, null);
        } catch (ApiException e) {
            log.error("create uid:{} namespace:{} svc error,msg:{}", uid, namespace, e.getResponseBody());
            return null;
        }

        return resp;
    }

    public boolean deleteSvc(String uid, String namespace) {
        V1Service v1Service;
        try {
            v1Service = coreV1Api.deleteNamespacedService(uid, namespace, null, null,
                    null, null, null, new V1DeleteOptions());
        } catch (ApiException e) {
            return false;
        }
        if (v1Service == null) {
            return false;
        }

        return true;
    }

    public V1Service getSvc(String uid, String namespace) {
        V1Service svc = null;
        try {
            svc = coreV1Api.readNamespacedService(uid, namespace, null);
        } catch (ApiException e) {

        }

        return svc;
    }

    public boolean exist(String namespace, String uid) {
        V1Service svc = getSvc(uid, namespace);
        if (svc == null) {
            return false;
        }

        return true;
    }
}
